/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.interceptor;

import io.jboot.Jboot;
import io.jboot.exception.JbootAssert;
import io.jplus.admin.model.Log;
import io.jplus.admin.service.LogService;
import io.jplus.core.annotation.LogConfig;
import io.jplus.core.exception.JplusException;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
import java.util.Date;

public class JplusLogInterceptor implements MethodInterceptor {

    LogService logService;

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        if (logService == null) {
            logService = Jboot.bean(LogService.class);
        }
        Class targetClass = methodInvocation.getThis().getClass();
        Method method = methodInvocation.getMethod();
        LogConfig logConfig = method.getAnnotation(LogConfig.class);
        if (logConfig == null) {
            return methodInvocation.proceed();
        }

        if (logConfig.logType() == null) {
            JbootAssert.assertNotNull(logConfig.logType(), "logType is not null!");
            return methodInvocation.proceed();
        }
        Log log = createLog(logConfig, method);
        try {
            log.setClassname(targetClass.getName());
            //调用执行
            Object result = methodInvocation.proceed();
            logService.save(log);
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            log.setSucceed("0");
            log.setMessage(String.format("错误信息", throwable.getMessage()));
            logService.save(log);
            throw new JplusException(throwable);
        }
    }

    private Log createLog(LogConfig logConfig, Method method) {
        Log log = new Log();
        log.setLogname(logConfig.logName());
        log.setLogtype(logConfig.logType());
        log.setCreatetime(new Date());
        log.setMethod(method.getName());
        log.setSucceed("1");
        return log;
    }

}
